﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace SaveTheQueen.Component
{
    public class ImageSprite : Sprite
    {
        private string resource;
        private Texture2D texture;

        public Texture2D Texture
        {
            get { return texture; }
            protected set { texture = value; CalcScaleFactor(Size); CalcCenterAndCenterOffset(sourceSize()); }
        }
        protected override Vector2 sourceSize()
        {
            if (texture != null)
                return new Vector2(texture.Width, texture.Height);
            else
                return Vector2.Zero;
        }


        public ImageSprite(string resource, int x, int y, int w, int h, GameObject owner, Game game)
            : base(x, y, w, h, owner, game)
        {
            this.resource = resource;
        }

        protected override void LoadContent()
        {
            texture = Game.Content.Load<Texture2D>(resource);

            base.LoadContent();
        }
        protected override void UnloadContent()
        {
            texture.Dispose();
            base.UnloadContent();
        }

        public override void Draw(GameTime gameTime)
        {
            SpriteBatch sb = ((SpriteBatch)Game.Services.GetService(typeof(SpriteBatch)));
            if (Shader != null)
            {   // End the pass that were happening and start another one with the transform and effect.
                sb.End();
                sb.Begin(SpriteSortMode.Deferred, null, null, null, null, Shader, Core.ScaleMatrix);

                sb.Draw(
                    texture,
                    Position + Offset + centerOffset,
                    null,
                    Tint,
                    Rotation,
                    realCenter,
                    innerScale * Scale,
                    Effect,
                    Depth);

                sb.End();   // End current pass and start the defaut one again, so the following objects won't be affected.
                sb.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Core.ScaleMatrix);
            }
            else
            {
                sb.Draw(
                    texture,
                    Position + Offset + centerOffset,
                    null,
                    Tint,
                    Rotation,
                    realCenter,
                    innerScale * Scale,
                    Effect,
                    Depth);
            }
            base.Draw(gameTime);
        }
    }
}
